package com.gxa.weixing.pc.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.gxa.weixing.core.common.JsonResult;
import com.gxa.weixing.core.exception.BusinessException;
import com.gxa.weixing.core.pojo.GoodsConsumeVO;
import com.gxa.weixing.core.pojo.ShopGoodsConsume;
import com.gxa.weixing.pc.service.ShopGoodsConsumeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lijianmin
 * @date 2022/01/06  16:02:14
 */
@RestController
@RequestMapping("/shopGoodsConsume")
@Api(tags = "门店商品自耗Api")
public class ShopGoodsConsumeController {

    @Resource
    private ShopGoodsConsumeService shopGoodsConsumeService;

    /**
     * 根据特定条件获取门店自耗商品列表的接口
     *
     * @param map 条件
     *            name: 商品名称 模糊
     *            shopName:所属门店名称
     *            state: 审核状态 (0 审核中/1 审核通过/ 2审核失败)
     *            page:页码
     *            size:每页数据量
     * @return 返回查询结果
     */
    @PostMapping("/getList")
    @ApiOperation("根据特定条件获取门店自耗商品列表的接口")
    @ApiImplicitParam(name = "map", value = "map", paramType = "body")
    public Map<String, Object> getList(@RequestBody Map<String, Object> map) throws BusinessException, ParseException {
        PageInfo<Map<String, Object>> list = shopGoodsConsumeService.getList(map);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.setData(list.getList());
        jsonResult.put("count",list.getTotal());
        return jsonResult.getDataMap();
    }

    /**
     * 门店自耗商品导出接口
     * @param map 搜索条件
     *              name: 商品名称 模糊
     *              shopName:所属门店名称
     *              state: 审核状态 (0 审核中/1 审核通过/ 2审核失败)
     * @return 返回是否成功
     */
    @PostMapping("/export")
    @ApiOperation("门店自耗商品导出接口")
    public void export(@RequestBody Map<String, Object> map,HttpServletResponse response) throws BusinessException, IOException, ParseException {
        // 获取 根据条件查询到的集合
        List<Map<String, Object>> list = shopGoodsConsumeService.getList(map).getList();
        // 创建一个空的集合 泛型为GoodsConsumeVO
        List<GoodsConsumeVO> all = new ArrayList<>();
        // 遍历查询到的集合
        for (Map<String, Object> maps : list) {
            // 将map转换为JSON字符串
            String jsonString = JSONUtils.toJSONString(maps);
            // 将JSON字符串转化为对象
            GoodsConsumeVO goodsConsumeVO = JSON.parseObject(jsonString, GoodsConsumeVO.class);
            // 将对象装入新创建的集合
            all.add(goodsConsumeVO);
        }
        // 语雀导出
        // ExportUtil.easyExcelExport(voList, GoodsConsumeVO.class,"门店自耗记录","门店自耗记录表sheet1",httpServletResponse);


        // 工作簿对象(excel文件对象)
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("门店自耗记录表");
        String fileName = "门店自耗记录表.xls"; // 将文件名中的中文部分被URL编码后的内容进行解析, 最终还是显示为中文状态
        fileName = URLEncoder.encode(fileName, "utf-8");

        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = {"编号","商品编号", "商品名称", "推荐语","销售价格(元)", "所属门店", "消耗数量", "申请人账号", "申请时间", "申请备注", "审核时间", "审核状态", "审核人"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            //先把文字转换为标准的富文本格式
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把转换后的字段名添加到表头行上
            cell.setCellValue(text);
        }
        //准备将时间格式处理为标准日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 添加数据行:
        int rowNum = 1;
        for (GoodsConsumeVO item : all) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(item.getId());
            dataRow.createCell(1).setCellValue(item.getGoodsId());
            dataRow.createCell(2).setCellValue(item.getGoodsName());
            dataRow.createCell(3).setCellValue(item.getPromotionStatement());
            dataRow.createCell(4).setCellValue(item.getGoodsPrice().toString());
            dataRow.createCell(5).setCellValue(item.getShopName());
            dataRow.createCell(6).setCellValue(item.getConsumeNumber());
            dataRow.createCell(7).setCellValue(item.getApplyName());
            dataRow.createCell(8).setCellValue(item.getApplyTime());
            dataRow.createCell(9).setCellValue(item.getApplyRemarks());
            dataRow.createCell(10).setCellValue(item.getAuditName());
            dataRow.createCell(11).setCellValue(item.getAuditTime());
            dataRow.createCell(12).setCellValue(item.getAuditRemarks());
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        //告诉浏览器, 以附件方式打开,而不是页面上浏览
        response.setHeader("Content-disposition", "attachment;filename=" + fileName+";"+"filename*=utf-8''"+fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

    /**
     * 自耗申请审核接口
     *
     * @param shopGoodsConsume 自耗申请对象
     * @return 返回是否成功
     */
    @SneakyThrows
    @PostMapping("/audit")
    @ApiOperation("自耗申请审核接口")
    @ApiImplicitParam(name = "shopGoodsConsume", value = "shopGoodsConsume", paramType = "body")
    public Map<String, Object> audit(@RequestBody ShopGoodsConsume shopGoodsConsume) throws BusinessException {
        shopGoodsConsumeService.audit(shopGoodsConsume);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("操作成功");
        return jsonResult.getDataMap();
    }


    /**
     * 门店自耗申请接口
     *
     * @param shopGoodsConsume 门店自耗对象
     * @return 返回是否成功
     */
    @PostMapping("/add")
    @ApiOperation("添加门店库存的接口")
    @ApiImplicitParam(name = "shopGoodsConsume", value = "shopGoodsConsume", paramType = "body")
    public Map<String, Object> add(@RequestBody ShopGoodsConsume shopGoodsConsume) throws BusinessException {
        shopGoodsConsumeService.add(shopGoodsConsume);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("添加成功");
        return jsonResult.getDataMap();
    }


}
